﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;

namespace FDSimpleModelGenerator.Common.Mvc
{
    /// <summary>
    /// 用户上下文
    /// </summary>
    public class UserContext
    {
        public static UserContext Current { get; } = new UserContext();
        private HttpContext _context;

        public HttpContext Context => _context;

        public void Init(HttpContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 登录到信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task LoginAsync(string userName, int userId)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Sid,userId.ToString()),
            new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.Role, "admin"),
                new Claim("LastChanged", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
            };
            var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperies = new AuthenticationProperties
            {
                ExpiresUtc = DateTimeOffset.UtcNow.AddDays(7)
                //RedirectUri = "/Login"
            };
            await _context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimIdentity), authProperies);
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task LogoutAsyn()
        {
            await _context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}
